# -*- coding: utf-8 -*-

from google.appengine.ext import db
import datetime
from xml.dom import minidom

class NStation(db.Model):
  stid = db.IntegerProperty()
  name = db.StringProperty()
  lastupdate = db.StringProperty()
  coordinates = db.StringProperty()
  available = db.IntegerProperty()
  freespace = db.IntegerProperty()
  
  def from_xml(self, placemark):
    description = placemark.getElementsByTagName('description')[0]
    xml = description.firstChild.nodeValue
    dom = minidom.parseString(xml.encode('utf-8'))
    divs = dom.firstChild.getElementsByTagName('div')
    self.stid = int(divs[0].firstChild.nodeValue.split(" - ")[0])
    self.name = divs[0].firstChild.nodeValue.split(" - ")[1]
    self.available = int(divs[2].childNodes[0].nodeValue)
    self.freespace = int(divs[2].childNodes[2].nodeValue)
    point = placemark.getElementsByTagName('Point')[0]
    self._parse_coordinates(point.firstChild.firstChild.nodeValue)

  def _parse_coordinates(self, coords):
    coords = coords.replace('?', '')
    coords = coords.split(',')
    coordinates = map(unicode, coords)
    self.coordinates = u",".join(coordinates)

  def set_timestamp(self, timestamp):
    self.lastupdate = timestamp

  def to_dict(self):
    return dict(stid=self.stid, name=self.name, timestamp=self.lastupdate,\
      coordinates=self.coordinates, available=self.available, freespace=self.freespace)
